package com.provider.test.registry.impl;

import com.provider.test.registry.RegistryBO;
import com.common.test.zk.RegistryCenterConfig;
import com.provider.test.registry.RegistryCenterService;
import com.provider.test.registry.RegistryIPPortBO;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class RegistryCenterServiceImpl implements RegistryCenterService {


    private CuratorFramework curatorFramework;

    {
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(RegistryCenterConfig.CONNECTING_STR)
                .sessionTimeoutMs(RegistryCenterConfig.SESSION_TIMEOUT)
                .retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
        curatorFramework.start();
    }



    @Override
    public void registryServer(RegistryBO registryBO) {


        String serviceNodePath = RegistryCenterConfig.NAMESPACE + "/" + registryBO.getServerName();
        try {
            //如果serviceNodePath（/rpcNode/userService）不存在就创建
             Stat stat = curatorFramework.checkExists().forPath(serviceNodePath);
            if (stat==null){
                //持久化节点
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(serviceNodePath,RegistryCenterConfig.DEFAULT_VALUE);
            }
            //注册的服务的节点路径
             RegistryIPPortBO registryIPPortBO = registryBO.getRegistryIPPortBO();
           String serverIp = registryIPPortBO.getServerIp();
             String serverPort = registryIPPortBO.getServerPort();
            String addressPath = serviceNodePath+"/"+serverIp+":"+serverPort;
            //临时节点
            String rsNode = curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(addressPath, RegistryCenterConfig.DEFAULT_VALUE);
        } catch (Exception e) {
            throw new RuntimeException("注册服务出现异常！",e);
        }

    }


}
